/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.cmu.lti.sepia.data.db.IRJudgmentResultDAO;
import edu.cmu.lti.sepia.data.db.QAJudgmentResultDAO;
import edu.cmu.lti.sepia.data.db.SQL;
import edu.cmu.lti.sepia.data.db.TaskDAO;
import edu.cmu.lti.sepia.data.db.TopicDAO;
import edu.cmu.lti.sepia.data.session.SessionManager;
import edu.cmu.lti.sepia.infra.topic.model.Task;
import edu.cmu.lti.sepia.infra.topic.model.Topic;
import edu.cmu.lti.sepia.util.Logger;
import edu.cmu.lti.sepia.util.ServletUtil;

//Protected variation realized by hiding jexcelapi from this class 
public class ExcelExporter extends HttpServlet {

  private static final long serialVersionUID = 1L;

  public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
    SQL sql = new SQL();
    
	  try {
	    Logger.log( sql, request.getSession(), "EXPORT TOPICS (EXCEL)", "" );
	    
	    ServletUtil s = new ServletUtil( request );
	    String taskNameShort;
	    if ( request.getParameter("taskNameShort")!=null ) {
	      taskNameShort = (String)request.getParameter("taskNameShort");
	      SessionManager.storeTask(sql, taskNameShort, request.getSession());
	    } else {
	      taskNameShort = (String)request.getSession().getAttribute("taskNameShort");
	    }
	    
	    int userId = s.readInt("userId", -1);
	    String lang = s.readString("targetLang", "JA");
	    String type = (String)request.getParameter("type");
	    
	    if (type.matches("q|gs")) {
	      toTopicExcel(request, response, sql, taskNameShort, userId);
	    } else if (type.matches("qrels")) {
	      toQrelsExcel(request, response, sql, taskNameShort, lang);
	    } else if (type.matches("qa_judgment")) {
	      toQAJudgmentExcel(request, response, sql, taskNameShort, lang);
	    }
	    
	  } catch (Exception e) {
	    throw new ServletException("Exception in Excel Exporter Servlet", e);
	  } finally {
	    try {
	      sql.close();
	    } catch (Exception e) {}
	  }
	}
  
  private void toTopicExcel( HttpServletRequest request, HttpServletResponse response, SQL sql, String taskNameShort, int userId )
    throws Exception {
    String type = (String)request.getParameter("type");
    boolean selectedOnly = request.getParameter("selected")!=null;

    List<Topic> topics = TopicDAO.getGoldStandard( sql, taskNameShort, userId, null );
    Task task = TaskDAO.findByTaskNameShort(sql, taskNameShort);

    TopicDAO.removeSimilarNuggets(topics);
    TopicDAO.generateExternalIds(topics,task.getTrgLang(),4);
    if (selectedOnly) {
      TopicDAO.removeUnselected(topics);
    }
    
    String postfix = "_"+(type.equals("q")?"topics":"goldstandard");
    
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=\""+taskNameShort+postfix+".xls\"");
    
    if (type.equals("gs")) {
      TopicDAO.toGoldStandardExcel(topics, response.getOutputStream(), task.getTrgLang()); //task.getSrcLang(), 
    } else if (type.equals("q")) {
      TopicDAO.toQuestionExcel(topics, response.getOutputStream(), task.getTrgLang());
    }
  }
  
  private void toQrelsExcel( HttpServletRequest request, HttpServletResponse response, SQL sql, String taskNameShort, String lang )
  throws Exception {
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=\""+taskNameShort+"_qrels.xls\"");    
    IRJudgmentResultDAO.exportQrelsInExcel(sql, taskNameShort, lang, response.getOutputStream());
  }
  
  private void toQAJudgmentExcel( HttpServletRequest request, HttpServletResponse response, SQL sql, String taskNameShort, String lang )
  throws Exception {
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=\""+taskNameShort+"_qa_judgment.xls\"");    
    QAJudgmentResultDAO.exportJudgmentsInExcel(sql, taskNameShort, lang, response.getOutputStream());
  }
  
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    doGet(request, response);
  }
}
